package org.example.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.captcha.model.CaptchaInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Autowired
    private CaptchaInfo captchaInfo;

    private static long VALIDI_TIME = 60 *1000;

    @RequestMapping("/get")
    public void getCaptcha(HttpSession session,HttpServletResponse response) {
        ICaptcha captcha = CaptchaUtil.createLineCaptcha(captchaInfo.getWidth(), captchaInfo.getHeight());
        try {
            captcha.write(response.getOutputStream());
            //禁止缓存
            response.setHeader("Pragma", "No-cache");
            //设置返回类型
            response.setContentType("image/jpeg");
            //打印验证码
            System.out.println(captcha.getCode());
            //存储session
            session.setAttribute(captchaInfo.getSession().getCode(), captcha.getCode());
            session.setAttribute(captchaInfo.getSession().getDate(), System.currentTimeMillis());

            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
    public Boolean check(String captchaCode,HttpSession session) {
        //校验参数，是否和session中的一致
        if (!StringUtils.hasLength(captchaCode)) {
            return false;
        }
        String sessionCode = (String) session.getAttribute(captchaInfo.getSession().getCode());
        Long sessionDate = (Long) session.getAttribute(captchaInfo.getSession().getDate());
        if (captchaCode.equalsIgnoreCase(sessionCode) && (sessionDate != null) && (System.currentTimeMillis()-sessionDate) < VALIDI_TIME) {
            return true;
        }
        return false;
    }
}
